/**
 * 脱敏数据
 * @param {string} val 值
 * @param {'mobile'|'idcard'|'name'|'email'|'guarantorName'|'guarantorOrgName'} type
 * @return {*|string}
 */
function desensitizeString(val, type) {
  if (!val) return ''
  type = String(type).toLowerCase().trim()

  const strategyMap = {
    name: () => {
      // 普通姓名
      // if (val.length <= 2) {
      //   const name = val.replace(/.*(?=[\u4e00-\u9fa5])/,'*')
      //   return name
      // } else {
      // return val.replace(/(?<=[\u4e00-\u9fa5]).*/, '**')
      const chars = [...val]
      if (chars.length == 1) return '*'
      if (chars.length == 2) return chars[0] + '*'
      else return (chars[0] || '') + '*' + (chars.at(-1) || '')
    },

    guarantorname: () => {
      // 保证人名称
      const chars = [...val]

      if (chars.length <= 2) {
        // 小于两个字符
        return chars[0] + '*'.repeat(chars.length - 1)
      } else if (chars.length == 3) {
        // 等于于3个字符
        return chars[0] + '*'.repeat(chars.length - 2) + chars.at(-1)
      } else if (chars.length > 5) {
        // 如果大于5个字符
        return val
      } else {
        // 大于3个字符且小于等于5个字符
        const match = val.match(/(夫妻|夫妇)/)
        if (match) {
          const startIdx = match?.index,
            matchText = match[0],
            preChars = chars.slice(0, startIdx),
            sufChars = chars.slice(startIdx + matchText.length)
          if (chars.length == 4) return preChars[0] + '*' + matchText
          // console.log('matchText', matchText, match, sufChars)
          return preChars[0] + '*'.repeat(preChars.length - 2) + preChars.at(-1) + matchText + sufChars.join('')
        }
        return chars[0] + '*'.repeat(chars.length - 1) + chars.at(-1)
      }
    },

    guarantororgname: () => {
      // 保证人机构名称
      if (val?.length > 5) {
        //
        return val
      }
      return desensitizeString(val, 'guarantorName')
    },

    idcard: () => {
      // 身份证
      return val.replace(/^(.{3})(?:\d+)(.{4})$/, '$1**************$2')
    },

    mobile: () => {
      // 手机号
      return val.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    },

    address: () => {
      // 地址
      return val.replace(/[0-9a-zA-Z]/g, 'x')
    },

    email: () => {
      // 邮箱
      if (String(val).indexOf('@') > 0) {
        let limitLength = 1
        let str = val.split('@'),
          _s = ''
        if (str[0].length > limitLength) {
          for (let i = 0; i < str[0].length - limitLength; i++) {
            _s += '*'
          }
        }
        return str[0].substr(0, limitLength) + _s + '@' + str[1]
      }
    },

    default: () => {
      // 默认
      return ''
    }
  }
  const run = strategyMap[type] || strategyMap.default
  return run() || ''
}
export default desensitizeString

// console.log(desensitizeString('卞鹏飞夫妇', 'guarantorOrgName'))
